package com.xgkj.videodemo;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.storage.StorageManager;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MainActivity extends Activity implements SurfaceHolder.Callback,View.OnClickListener,View.OnTouchListener,MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnCompletionListener,MediaPlayer.OnErrorListener,MediaPlayer.OnPreparedListener,MediaPlayer.OnVideoSizeChangedListener{
    private final static String TAG = MainActivity.class.getSimpleName();
    private Button playBtn;
    private Button pauseBtn;
    private Button stopBtn;
    private SurfaceView mSurfaceView;
    private SurfaceHolder surfaceHolder;
    private MediaPlayer player;
    private StorageManager mStorageManager;
    private Method mMethodGetPaths;
    private Context mContext;
    private String[] paths;
    private boolean isMove;
    private float currentX;
    private float currentY;
    private float scrollX;
    private float scrollY;
    private float needX;
    private float needY;
    private boolean isFirst = false;
    private boolean isSound = false;
    private boolean isScreenLight = false;
    private boolean isProgressMove = false;
    private AudioManager audioManager;
    private int screenMode= 0;
    private int nowBrightnessValue = 0;
    private int width;
    private int height;
    private int currentPosition = 0;
    private int mVideoWidth;
    private int mVideoHeight;
    boolean isPrepared= false;
    boolean isVideoKnow = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        getPath();
        initView();
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;
        height = dm.heightPixels;

    }

    private void getPath() {
        mStorageManager = (StorageManager) mContext.getSystemService(Activity.STORAGE_SERVICE);
        try {
            mMethodGetPaths = mStorageManager.getClass().getMethod("getVolumePaths");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        paths =  getVolumePaths();
        for (int i=0;i<paths.length;i++) {
            Log.e(TAG, "存储路径" +i+":"+ paths[i]);
        }
    }

    private void initView() {
        mSurfaceView = (SurfaceView) findViewById(R.id.video);
        playBtn = (Button) findViewById(R.id.play);
        pauseBtn = (Button) findViewById(R.id.pause);
        stopBtn = (Button) findViewById(R.id.stop);
        surfaceHolder = mSurfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        playBtn.setOnClickListener(this);
        pauseBtn.setOnClickListener(this);
        stopBtn.setOnClickListener(this);
//        playBtn.setOnTouchListener(this);
        mSurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        isMove = false;
                        isFirst = false;
                        currentX = event.getRawX();
                        currentY = event.getRawY();
                        currentPosition = player.getCurrentPosition();
                        try {
                            screenMode = Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_BRIGHTNESS_MODE);
                        } catch (Settings.SettingNotFoundException e) {
                            e.printStackTrace();
                        }
                        Log.e(TAG,"亮度模式："+screenMode);

                        break;
                    case MotionEvent.ACTION_MOVE:
                        isMove = true;
                        scrollX = event.getRawX();
                        scrollY = event.getRawY();
                        needX = scrollX - currentX;
                        needY = scrollY - currentY;
                        if (!isFirst){
                            isFirst = true;
                            if (Math.abs(needX)<Math.abs(needY)){
                                if (currentX<= (width/2)) {
                                    isScreenLight = true;
                                }else {
                                    isSound = true;
                                }
                            }else{
                                isProgressMove = true;
                            }
                        }

                        Log.e(TAG,"滑动距离："+needY+"声音:"+isSound+"亮度:"+isScreenLight+"视频进度:"+isProgressMove+"当前X:"+currentX);


                        if (isSound){
                            int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                            int current = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//                            Log.e(TAG,"当前音量："+current+"最大音量："+max);
                            if (current>=0 && current<=max){
                                if (needY<-50){
//                                    Log.e(TAG,"增加声音");
                                    currentY = scrollY;
                                    audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,0);
                                }else if(needY>50){
//                                    Log.e(TAG,"减少声音");
                                    currentY = scrollY;
                                    audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,0);
                                }
                                Log.e(TAG,"当前音量:"+audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
                            }
                        }

                        if (isScreenLight){
                            if (screenMode == 1){
                                Settings.System.putInt (getContentResolver(),Settings.System.SCREEN_BRIGHTNESS_MODE,Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
                            }

                            try {
                                nowBrightnessValue = Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_BRIGHTNESS);
                            } catch (Settings.SettingNotFoundException e) {
                                e.printStackTrace();
                            }
                            if (nowBrightnessValue>=0 && nowBrightnessValue<=255){
                                if (needY<-10){
                                    currentY = scrollY;
                                    if (nowBrightnessValue<255) {
                                        nowBrightnessValue+=10;
                                    }
                                    if (nowBrightnessValue>255){
                                        nowBrightnessValue=255;
                                    }
                                }else if (needY >10){
                                    currentY = scrollY;
                                    if (nowBrightnessValue>0){
                                        nowBrightnessValue-=10;
                                    }
                                    if (nowBrightnessValue<0){
                                        nowBrightnessValue = 0;
                                    }
                                }
                            }
                            Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_BRIGHTNESS,nowBrightnessValue);
                            Log.e(TAG,"当前亮度:"+nowBrightnessValue);
                        }

                        if (isProgressMove){
                            if (needX>0) {
                                currentPosition += 1000;
                            }else {
                                currentPosition -=1000;
                            }
                            Log.e(TAG,"当前进度:"+currentPosition);
                        }

                        break;
                    case MotionEvent.ACTION_UP:
                        Log.e(TAG,"手指弹起");
                        if (!isMove) {
                            if (player.isPlaying()) {
                                player.pause();
                            } else {
                               play();
                            }
                        }else {
                            if (isScreenLight) {
                                Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, screenMode);
                                WindowManager.LayoutParams lp = getWindow().getAttributes();

                                lp.screenBrightness = Float.valueOf(nowBrightnessValue) * (1f / 255f);
                                Log.e("lxy", "set  lp.screenBrightness == " + lp.screenBrightness);
                                getWindow().setAttributes(lp);
                            }

                            if (isProgressMove){
                                player.seekTo(currentPosition);
//                                player.start();
                            }
                        }

                        isSound = false;
                        isScreenLight = false;
                        isProgressMove = false;
                        break;
                }
                return true;
            }
        });


    }

    public String[] getVolumePaths() {
        String[] paths = null;
        try {
            paths = (String[]) mMethodGetPaths.invoke(mStorageManager);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return paths;
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
//        String url = "/sdcard/360/VIDEO0002.mp4";
            String url = "http://123.56.197.123/Honor.mp4";
//         String url = paths[0]+"/Movies/Honor.mp4";
        File file = new File(url);
        Log.e(TAG,"视频大小："+file.length());
        Uri uri = Uri.parse(url);

        try {
            player = new MediaPlayer();//MediaPlayer.create(mContext,uri);
            player.setDisplay(surfaceHolder);
            player.setOnBufferingUpdateListener(this);
            player.setOnCompletionListener(this);
            player.setOnPreparedListener(this);
            player.setOnVideoSizeChangedListener(this);
            player.setOnErrorListener(this);
//            player.setDataSource(mContext,uri);
            player.setDataSource(url);
            player.prepareAsync();
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        } catch (IOException e) {
            e.printStackTrace();
        }



//        try {
//            player.setDataSource(paths[0]+"/Movies/Honor.mp4");
//            player.prepare();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.e(TAG,"得到的方向:"+getResources().getConfiguration().orientation);
        Log.e(TAG,newConfig.orientation+"屏幕方向");
        if (newConfig.orientation== ActivityInfo.SCREEN_ORIENTATION_USER){
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
            mVideoHeight = width;
            mVideoWidth = height;
            startVideoPlayback();
        }else if (newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            mVideoWidth = width;
            mVideoHeight = width*9/16;
            startVideoPlayback();
        }
    }

    private void startVideoPlayback() {
        Log.e(TAG, "startVideoPlayback宽:"+mVideoWidth+"高:"+mVideoHeight);
        if (isPrepared && isVideoKnow) {
            surfaceHolder.setFixedSize(mVideoWidth, mVideoHeight);
            player.start();
        }
    }

    private void play(){
        if (isPrepared && isVideoKnow) {
            playBtn.setEnabled(false);
            pauseBtn.setEnabled(true);
            player.start();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.play:
                Log.e(TAG,"点击play");
               play();
                break;
            case R.id.pause:
                playBtn.setEnabled(true);
                pauseBtn.setEnabled(false);
                player.pause();
                break;
            case R.id.stop:
//                player.stop();
//                Intent intent = new Intent(Intent.ACTION_VIEW);
                //http://dlqncdn.miaopai.com/stream/MVaux41A4lkuWloBbGUGaQ__.mp4 file:///storage/emulated/0/Movies
//                Uri uri = Uri.parse("http://app.chiboker.com/Honor.mp4");
//                Log.e(TAG,uri.toString());
//                intent.setDataAndType(uri,"video/mp4");
//                startActivity(intent);
                Intent adIntent = new Intent(Intent.ACTION_VIEW);
                String url ="";
                adIntent.setData(Uri.parse(url));
                // PalLog.e("AD",adIntent.toString());

                try {
                    mContext.startActivity(adIntent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (player.isPlaying()){
            player.stop();
        }
        player.release();
        player = null;
        super.onDestroy();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction()==MotionEvent.ACTION_DOWN)return false;
        if (event.getAction()==MotionEvent.ACTION_MOVE) return false;
        player.start();
        playBtn.setSelected(true);
        Log.e(TAG,"ACTION_UP");
        return false;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        Log.e(TAG,"onBufferingUpdate"+percent);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        Log.e(TAG,"onCompletion");
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        Log.e(TAG,"onPrepared");
        isPrepared = true;
        startVideoPlayback();
    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        Log.e(TAG,"onVideoSizeChanged");
        mVideoWidth=width;
        mVideoHeight = height;
        isVideoKnow = true;
        startVideoPlayback();
    }
}
